package com.cgt.xiaotao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgt.common.domain.dto.LoginFormDTO;
import com.cgt.common.domain.dto.LoginUserDTO;
import com.cgt.common.exception.XiaoTaoException;
import com.cgt.common.utils.BeanUtils;
import com.cgt.common.utils.R;
import com.cgt.common.utils.UserContext;
import com.cgt.xiaotao.oss.client.OssFileClient;
import com.cgt.xiaotao.user.domain.dto.UserAddressDTO;
import com.cgt.xiaotao.user.domain.po.User;
import com.cgt.xiaotao.user.domain.po.UserAddress;
import com.cgt.xiaotao.user.domain.query.UserQuery;
import com.cgt.xiaotao.user.domain.vo.UserVO;
import com.cgt.xiaotao.user.mapper.UserMapper;
import com.cgt.xiaotao.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    private final OssFileClient ossFileClient;

    @Override
    public UserVO queryUser() {
        Long userId = UserContext.getUser();
        User user = userMapper.selectById(userId);
        UserVO userVO = BeanUtils.copyBean(user, UserVO.class);
        return userVO;
    }

    @Override
    public LoginUserDTO queryUserDetail(LoginFormDTO loginDTO, boolean isStaff) {
        String username = loginDTO.getUsername();
        String phone = loginDTO.getPhone();
        String email = loginDTO.getEmail();
        String password = loginDTO.getPassword();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (username != null) {
            wrapper.eq("username", username);
        } else if (phone != null) {
            wrapper.eq("phone", phone);
        } else if (email != null) {
            wrapper.eq("email", email);
        }
        wrapper.eq("password", password);
        User user = userMapper.selectOne(wrapper);
        if (user != null) {
            LoginUserDTO loginUserDTO = new LoginUserDTO();
            loginUserDTO.setUserId(user.getId());
            loginUserDTO.setRememberMe(loginDTO.getRememberMe());
            loginUserDTO.setRoleId((long) (isStaff ? 1 : 2));
            return loginUserDTO;
        }
        throw new XiaoTaoException(404, "用户不存在");
    }

    //根据手机号查询用户id
    @Override
    public Long exchangeUserIdWithPhone(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        User user = userMapper.selectOne(wrapper);
        return user != null ? user.getId() : null;
    }

    //更新用户头像
    @Override
    public void updateAvatar(MultipartFile file) {
        // 获取用户ID
        Long userId = UserContext.getUser();

        // 调用OSS服务上传文件
        R<String> result = ossFileClient.upload(file);

        if (result.getCode() == 200) {
            String avatarUrl = result.getData();
            // 更新用户头像URL到数据库
            User user = new User();
            user.setId(userId);
            user.setAvatarUrl(avatarUrl);
            userMapper.updateById(user);
        } else {
            throw new XiaoTaoException(500, "头像上传失败");
        }
    }

    @Override
    public String test() {
        Long user = UserContext.getUser();
        return "" + user;
    }

    @Override
    public void updateUser(UserQuery query) {
        Long userId = UserContext.getUser();
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userId);

        // 使用Map存储字段和值的映射关系
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("nickname", query.getNickname());
        fieldMap.put("username", query.getUsername());
        fieldMap.put("phone", query.getPhone());
        fieldMap.put("email", query.getEmail());
        fieldMap.put("gender", query.getGender());
        fieldMap.put("birthday", query.getBirthday());
        fieldMap.put("description", query.getDescription());

        // 只更新非空字段
        fieldMap.entrySet().stream()
                .filter(entry -> entry.getValue() != null)
                .forEach(entry -> updateWrapper.set(entry.getKey(), entry.getValue()));

        try {
            userMapper.update(null, updateWrapper);
        } catch (DuplicateKeyException e) {
            throw new XiaoTaoException(500, "用户名或手机号已存在");
        } catch (DataAccessException e) {
            throw new XiaoTaoException(500, "数据库访问异常");
        } catch (Exception e) {
            throw new XiaoTaoException(500, "更新用户信息失败");
        }
    }
}
